package com.xiang;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class ImageRotationExample {
  public static void main(String[] args) {
    String imagePath = "C:\\Users\\zeng_\\Pictures\\load(1)(1)\\旋转照片_test_rotated.jpg";

    try {
      // 读取图片
      BufferedImage image = ImageIO.read(new File(imagePath));

      // 检测旋转角度并矫正
      BufferedImage rotatedImage = correctRotation(image);

      // 保存矫正后的图片
      ImageIO.write(rotatedImage, "jpg", new File("C:\\Users\\zeng_\\Pictures\\load(1)(1)\\旋转照片_test_rotated3333.jpg"));

      System.out.println("图片旋转矫正完成。");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static BufferedImage correctRotation(BufferedImage image) {
    // 分析图片内容，检测旋转角度

    // TODO: 实现旋转角度检测算法

    int rotationAngle = 0; // 检测到的旋转角度

    // 根据旋转角度进行矫正
    BufferedImage rotatedImage = rotateImage(image, rotationAngle);
    return rotatedImage;
  }

  public static BufferedImage rotateImage(BufferedImage image, int angle) {
    // 执行旋转操作

    double radian = Math.toRadians(angle);
    double sin = Math.abs(Math.sin(radian));
    double cos = Math.abs(Math.cos(radian));
    int newWidth = (int) Math.round(image.getWidth() * cos + image.getHeight() * sin);
    int newHeight = (int) Math.round(image.getWidth() * sin + image.getHeight() * cos);

    BufferedImage rotatedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = rotatedImage.createGraphics();

    AffineTransform transform = new AffineTransform();
    transform.translate(newWidth / 2, newHeight / 2);
    transform.rotate(radian, 0, 0);
    transform.translate(-image.getWidth() / 2, -image.getHeight() / 2);
    g2d.drawImage(image, transform, null);
    g2d.dispose();

    return rotatedImage;
  }
}
